import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];//10个0
    }
    public  boolean isFull() {
        return this.usedSize == this.elem.length;
    }
    public  boolean isEmpty() {
        return this.usedSize == 0;
    }
    public int poll() {
        //先判断队列是否为空，为空则抛出异常
        if (isEmpty()){
            throw new RuntimeException("优先级队列为空");
        }
        int tmp=this.elem[0];
        this.elem[0]=this.elem[this.usedSize-1];
        this.usedSize--;
        shiftDown(0);
        return tmp;
    }
    public void push(int val) {

        if (isFull()){
            Arrays.copyOf(this.elem,this.elem.length*2);
        }
        this.elem[this.usedSize++]=val;
        shiftUp(this.usedSize-1);
    }
    public void shiftUp(int child) {
        int parent=(child-1)/2;
        while (parent>=0){
            if(this.elem[child]>this.elem[parent]){
                int tmp=this.elem[child];
                this.elem[child]=this.elem[parent];
                this.elem[parent]=tmp;
                child=parent;
                parent=(child-1)/2;
            }
            else{
                break;
            }
        }
    }
    public void shiftDown(int parent) {
        int child = 2*parent+1;
        //进入这个循环 说明最起码你有左孩子
        while (child < this.usedSize) {
            if(child+1 < this.usedSize && this.elem[child] < this.elem[child+1]) {
                child++;
            }
            //child所保存的下标，就是左右孩子的最大值
            if(this.elem[child] > this.elem[parent]) {
                int tmp = this.elem[child];
                this.elem[child] = this.elem[parent];
                this.elem[parent] = tmp;
                parent = child;
                child = 2*parent+1;
            }else {
                break;//如果孩子节点比父亲节点小 直接结束了
            }
        }
    }

    //1 4 18 7 .....
    public void createBigHeap(int[] array) {
        //把需要的数据 存放到elem当中 一会儿建堆的时候 直接操作 elem数组就可以了
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }

        for (int i = (this.usedSize-1-1)/2; i >= 0 ; i--) {
            shiftDown(i);
        }
    }

    public static void main(String[] args) {
        PriorityQueue<Integer> queue=new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        queue.offer(8);
        queue.offer(1);
        System.out.println(queue.peek());
    }
}
